<template>
  <div id="reviewDetail">
    <el-card class="box-card">
      <!--</div>-->
      <div class="info-item">
        <div>
          <span class="tipText">数据量</span>
          <span>{{detailData.dataNum}}</span>
        </div>
        <div>
          <span class="tipText">获取时间</span>
          <span>{{!!detailData.pushTime ? detailData.pushTime : '-' }}</span>
        </div>
      </div>
      <div class="info-item">
        <div>
          <span class="tipText">重单数</span>
          <span>{{detailData.repeatNum}}</span>
        </div>
        <div>
          <span class="tipText">接收时间</span>
          <span>{{!!detailData.insertTime ? detailData.insertTime : '-' }}</span>
        </div>
      </div>
      <div class="info-item">
        <div>
          <span class="tipText">重单确认倒计时</span>
          <span class="countDown">{{ countDownText }}</span>
        </div>
      </div>
    </el-card>

    <div class="select-group">
      <div class="items">
        <span class="items-text">是否重单</span>
        <el-select v-model.number="query.isRepeat" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in repeatList"
            :key="item.repeatId"
            :label="item.repeatName"
            :value="item.repeatId">
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="select-group">
      <div class="items">
        <span class="items-text">营销建议</span>
        <el-select v-model.number="query.advice" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in adviceList"
            :key="item.adviceId"
            :label="item.adviceName"
            :value="item.adviceName">
          </el-option>
        </el-select>
      </div>
    </div>

    <div class="select-group">
      <div class="items">
        <span class="items-text">手机号</span>
        <el-input
          placeholder="请输入手机号"
          v-model="query.phone">
        </el-input>
        <el-button @click="getList" size="medium"  type="success" class="el-icon-search"><span style="padding-left:5px;">查询</span></el-button>
      </div>
    </div>


    <el-table empty-text="暂无任何数据信息" :data="list" v-loading.body="listLoading" border fit style="width: 100%">
      <el-table-column align="center" label="ID" >
        <template slot-scope="scope">
          <span>{{ scope.row.customerId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{ !!scope.row.phone ? scope.row.phone : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="性别">
        <template slot-scope="scope">
          <span>{{ !!scope.row.sex ? (scope.row.sex == '1' ? '男' : '女' ) : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="营销建议">
        <template slot-scope="scope">
          <span>{{ !!scope.row.advice ? scope.row.advice : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="意向项目">
        <template slot-scope="scope">
          <span>{{ !!scope.row.item ? scope.row.item : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="数据备注">
        <template slot-scope="scope">
          <span>{{ !!scope.row.callRemarks ? scope.row.callRemarks : '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="320">
        <template slot-scope="scope">
          <div v-if="scope.row.status == '1'">
            <el-button @click="openRepeat(scope.row,1)" type="success" size="small">重单</el-button>
            <el-button @click="openRepeat(scope.row,2)" type="success" size="small">未重单</el-button>
          </div>
          <div v-else-if="scope.row.status == '2'">
            <el-button type="success" :disabled="true" size="small">已重单</el-button>
          </div>
          <div v-else-if="scope.row.status == '3'">
            <el-button @click="openRepeat(scope.row,3)" type="warning" size="small">未反馈</el-button>
          </div>
          <div v-else="scope.row.status == '4'">
            <el-button @click="openRepeat(scope.row,4)" type="primary" size="small">已反馈</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange" :current-page.sync="query.currentPage"
                     :page-sizes="[10,20,30,50]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog @close="cancelDialog" width="400px" :visible.sync="visible">
      <div v-if="clickStatus == '1'">
        <el-upload
          style="position: relative"
          class="avatar-uploader"
          :http-request="imgUpload"
          action=""
          drag
          name="file"
          accept="image/jpeg,image/gif,image/png,image/jpg"
          :show-file-list="false"
          :before-upload="beforeupload">
          <div :style="{backgroundImage: 'url(' + imgUrl + ')'}" v-if="imgUrl" class="avatar"></div>
          <i v-if="!imgUrl" class="el-icon-upload"></i>
          <div v-if="!imgUrl" class="el-upload__text">将文件拖到此处，{{ isIE() }} 或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2M</div>
        </el-upload>
      </div>
      <div v-else>
        未重单数据将可看到数据详情
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="sureCheckUpload">{{ clickStatus == '1' ? '确认并上传' : '确认未重单' }}</el-button>
      </div>
    </el-dialog>


    <el-dialog @close="cancelDialog('back_form')" top="10vh"  width="400px" title="请按实际情况填写用户数据反馈" :visible.sync="visible_back">
      <el-form :model="rowItems" :rules="backRule" ref="back_form">
        <el-form-item class="backForm" label="是否有效沟通"  :label-width="formLabelWidth">
          <el-radio-group v-model="rowItems.isCommunicate">
            <el-radio :label.number="1">是</el-radio>
            <el-radio :label.number="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="backForm" label="是否预约"  :label-width="formLabelWidth">
          <el-radio-group v-model="rowItems.isArrival">
            <el-radio :label.number="1">是</el-radio>
            <el-radio :label.number="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="backForm" label="是否有效沟通" :label-width="formLabelWidth">
          <el-radio-group v-model="rowItems.isBargain">
            <el-radio :label.number="1">是</el-radio>
            <el-radio :label.number="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="成交项目" :label-width="formLabelWidth">
          <el-input v-model="rowItems.deal"  auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成交金额" prop="money" :label-width="formLabelWidth">
          <el-input v-model.number.sync="rowItems.money" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="营销备注"  :label-width="formLabelWidth">
          <el-input type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入内容"
                    v-model.sync="rowItems.remarks"
                    auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible_back = false">取 消</el-button>
        <el-button type="primary" @click="upDateBackData('back_form')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { getFolderDataList ,changeRepeatStatus ,postFeedBack} from '@/api/dataReview';
  export default {
    name: "reviewDetail",
    data() {
      return {
        rowItems:{},
        formLabelWidth:'120px',
        imgParam:null,
        imgUrl:'',
        clickStatus:null,
        clickRowData:null,
        visible:false,
        visible_back:false,
        countDownText:'',
        detailData:{
          pushCount:20,
          repeatCount:20,
          pushTime:'2018-04-02 23:00',
          insertTime:'2018-04-02 23:00',
        },
        repeatList:[
          {repeatId:2,repeatName:'重单'},
          {repeatId:3,repeatName:'未重单'},
        ],
        adviceList:[
          {adviceId:1,adviceName:'可跟进'},
          {adviceId:2,adviceName:'需等待'},
        ],
        backRule:{
          money:[
            {type:'number',message:'请输入数字',trigger:'blur'}
          ]
        },
        listLoading:false,
        total:0,
        list:[],
        query: {
          folderId:'',
          advice:'',
          isRepeat: '',
          phone:'',
          pageSize:10,
          currentPage:1,
        },
      }
    },
    created(){
      this.query.folderId = this.$route.query['folderId'];
      this.getList();
    },
    mounted(){
      this.setCopyFunc();
    },
    methods: {
      isIE(){
        const ua =  window.navigator.userAgent;
        let rMsie = /(msie\s|rident.*rv:)([\w.]+)/;
        return rMsie.test(ua) ? '' : '或粘贴截图，';
      },
      setCopyFunc(){
        var that = this;
        document.addEventListener("paste", function (e) {
          var e = e || window.event;
          var cbd = e.clipboardData;
          var ua = window.navigator.userAgent;

          if(!that.visible && that.clickStatus != '1'){
            return
          }

          // 如果是 Safari 直接 return
          if ( !(e.clipboardData && e.clipboardData.items) ) {
            that.$message.error('您的浏览器不支持粘贴图片功能')
            return;
          }

          // Mac平台下Chrome49版本以下 复制Finder中的文件的Bug Hack掉
          if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" &&
            cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" &&
            ua.match(/Macintosh/i) && Number(ua.match(/Chrome\/(\d{2})/i)[1]) < 49){
            return;
          }

          for(var i = 0; i < cbd.items.length; i++) {
            var item = cbd.items[i];
            if(item.kind == "file"){
              var blob = item.getAsFile();
              if (blob.size === 0) {
                return;
              }
              that.beforeupload(blob);
            }
          }
        }, false);
      },
      beforeupload(file) {
          const isJPEG = file.type === 'image/jpeg';
          const isJPG = file.type === 'image/jpg';
          const isGIF = file.type === 'image/gif';
          const isPNG = file.type === 'image/png';
          const isLt2M = file.size / 1024 / 1024 < 1;
          if (!isJPEG && !isJPG && !isGIF && !isPNG) {
            this.$message.error('上传图片格式有误!');
            return false;
          }
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 1MB!');
            return false;
          }
        this.createImgUrl(file);
        //重新写一个表单上传的方法
        this.imgParam = file
        return false;
      },
      imgUpload(){
        console.log('覆盖默认')
      },
      filterObj(obj_target,requierKeyArr,flag){
        let obj = JSON.parse(JSON.stringify(obj_target));
        for(var k in obj){
          if(obj[k] == '' || (obj[k] instanceof Array ? !obj[k].length : false) || !obj[k] ){
            delete obj[k]
          }
        }
        if(!!requierKeyArr && requierKeyArr.length){
          for(var key in obj){
            if(!flag){
              requierKeyArr.indexOf(key) > -1 ? null : delete obj[key] ;
            }else {
              requierKeyArr.indexOf(key) > -1 ? delete obj[key] : null;
            }
          }
        }
        return obj
      },
      createImgUrl(file){
        //创建临时的路径来展示图片
        var windowURL = window.URL || window.webkitURL || window.mozURL;

        this.imgUrl=windowURL.createObjectURL(file);
      },
      sureCheckUpload(){
        let temp = new FormData();
        temp.append('folderId',this.query.folderId);
        temp.append('dataId',this.clickRowData.dataId);
        if(this.clickStatus == '1'){
          if(!!this.params){
            this.$message.error('请上传图片后再点确认');
            return false;
          }
          temp.append('isRepeat','2');
          temp.append('imgFile',this.imgParam);
        }else {
          temp.append('isRepeat','3');
        }
        changeRepeatStatus(temp).then(v=>{
          this.visible = false;
          this.$message.success(v.msg);
          this.getList();
        }).catch(v=>{
          this.visible = false;
          this.$message.error(v);
        })
      },
      getList(){
        var temp = this.filterObj(this.query);
        getFolderDataList(temp).then(response => {
          const temp = response.data;
          this.total = temp.totalRecord;
          this.detailData = temp;
          this.list = temp.dataList && temp.dataList.length ? temp.dataList : [] ;

          // // debugg
          // this.list[1].status = 3;

          this.listLoading = false;

          this.countDown(this.detailData.countDownSec);

        }).catch(res=>{
          this.listLoading = false
          this.$message.error(res)
        })
      },
      upDateBackData(form){
        this.$refs[form].validate(valid=>{
          if(!valid){
            this.$message.error('修改失败,请确认您的信息后再提交');
            return
          }

          let temp = this.filterObj(this.rowItems,
            ['folderId','dataId','isCommunicate','isArrival','isBargain','deal','money','remarks']
          )
          temp['isFeedback'] = 1;
          postFeedBack(temp).then(res=>{
            this.$message.success(this.clickStatus == '3' ? '添加反馈成功' : '修改反馈成功');
            this.visible_back = false;
            this.getList();
          }).catch(res=>{
            this.visible_back = false;
            this.$message.error(res)
          })
        })
      },
      openRepeat(rowData,clickStatus){
        let temp = Object.assign({},rowData);
        this.clickStatus = clickStatus;
        //rowData.status  //1:未确认显示2:已重单3:未反馈4:已反馈
        if(clickStatus == '1' || clickStatus == '2'){
          this.clickRowData = temp;
          this.visible = true;
        } else {
          this.rowItems = temp;
          this.visible_back = true;
        }
      },
      cancelDialog(userForm){  //重置;
        if(userForm){
          this.visible_back = false;
          //重置表单
          this.$refs[userForm].resetFields();
        }else{
          this.visible = false;
          this.imgParam  = null;
          this.imgUrl = '';
        }
        this.rowItems = {};
        this.clickStatus = '';
        this.clickRowData = {};
      },
      handleSizeChange(val) {
        this.query.pageSize = val
        this.getList()
      },
      handleCurrentChange(val){
        this.query.currentPage = val
        this.getList()
      },
      isEmptyObj(obj){
          for(var i in obj){//如果不为空，则会执行到这一步,返回true

            return true;
          }
          return false;
      },
      countDown(times) {
        var timer = null;
        var that = this;
        if(times*1 <= 0){
          that.countDownText = '已结束';
          return
        }
        timer = setInterval(() => {
          var day = 0,
            hour = 0,
            minute = 0,
            second = 0;//时间默认值
          if (times > 0) {
            day = Math.floor(times / (60 * 60 * 24));
            hour = Math.floor(times / (60 * 60)) - (day * 24);
            minute = Math.floor(times / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(times) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
          }
          // console.log(day + "天" + hour + "时" + minute + "分" + second + "秒");
          that.countDownText = day + "天" + hour + "时" + minute + "分" + second + "秒";
          times--;
          if (times <= 0) {
            clearInterval(timer);
            that.countDownText = '已结束';
            this.query.countDownFlag = 1;
            this.getList();
          }
        }, 1000);

      },
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  @import 'src/styles/variables.scss';
  #reviewDetail {
    .countDown {
      color:$mainBuleColor;
    }
    .backForm.el-form-item {
      margin-bottom: 10px;
    }
    .el-dialog__body {
      padding: 20px;
    }
    .avatar {
      display: inline-block;
      width: 100%;
      position: absolute;
      left: 0;
      height: 100%;
      right: 0;
      z-index:1999;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center center;
    }
    .info-item {
      margin: 25px 0px 15px 50px;
      > div {
        display: inline-block;
        min-width: 280px;
      }
      .tipText {
        display: inline-block;
        margin-right: 10px;
        min-width: 100px;
        text-align: right;
      }
    }
    .box-card {
      margin-bottom: 15px;
    }
    .textItem {
      margin: 10px 0px;
      width: 100%;
    }
  }
</style>
